﻿# 获取Bing当天壁纸（函数定义移到最前面）
function Get-BingWallpaper {
    <#
    .SYNOPSIS
    获取Bing当天壁纸并保存到脚本所在目录
    
    .DESCRIPTION
    从Bing图片API获取当天的壁纸信息，并固定保存到脚本所在目录的background.jpg
    
    .EXAMPLE
    Get-BingWallpaper
    # 将当天Bing壁纸保存到脚本所在目录的background.jpg
    #>
    [CmdletBinding()]
    param ()

    # 设置错误处理和进度显示
    $ErrorActionPreference = "Stop"
    $ProgressPreference = "SilentlyContinue"

    try {
        # 获取脚本路径的改进方法
        $scriptPath = $null
        if ($MyInvocation.MyCommand.Path) {
            $scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path
        }
        # 如果无法通过MyInvocation获取路径，尝试使用其他方法
        if (-not $scriptPath -and $PSCommandPath) {
            $scriptPath = Split-Path -Parent $PSCommandPath
        }
        # 如果仍然无法获取路径，使用当前工作目录
        if (-not $scriptPath) {
            $scriptPath = $PWD.Path
            Write-Warning "无法确定脚本文件路径，将使用当前工作目录: $scriptPath"
        }
        
        # 构建输出路径
        $outputPath = Join-Path -Path $scriptPath -ChildPath "background.jpg"
        if (-not $outputPath) {
            throw "无法构建输出路径"
        }

        # 获取Bing当天壁纸信息
        $apiUrl = "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1"
        $response = Invoke-WebRequest -Uri $apiUrl -UseBasicParsing
        $jsonData = $response.Content | ConvertFrom-Json

        # 构建完整图片URL
        $imageUrl = "https://cn.bing.com" + $jsonData.images[0].url

        # 下载并覆盖保存图片
        Invoke-WebRequest -Uri $imageUrl -OutFile $outputPath -UseBasicParsing
        Write-Host "当天壁纸已保存至: $outputPath" -ForegroundColor Green
        
        # 返回保存的路径
        return $outputPath
    }
    catch {
        Write-Host "获取壁纸失败: $_" -ForegroundColor Red
        return $null
    }
}


# 检查winget是否存在
$wingetPath = Get-Command -Name winget -ErrorAction SilentlyContinue

# 定义在新CMD窗口中运行命令的函数，1秒后自动关闭
function Run-InNewCmd {
    param(
        [string]$Command
    )
    # 使用timeout /t 1替代pause，1秒后自动关闭窗口
    start cmd.exe "/c `"$Command & echo 1秒后自动关闭窗口... & timeout /t 1 /nobreak`"" -Wait
}

if ($wingetPath) {
    # 已安装winget
    Write-Host "检测到 winget" -ForegroundColor Green
    
    Write-Host "WinGet 启动代理..."
    Run-InNewCmd "winget settings --enable ProxyCommandLineOptions"
    
    Write-Host "WinGet 移除源..."
    Run-InNewCmd "winget source remove winget --rainbow"
    
    Write-Host "WinGet 设置中科大源..."
    Run-InNewCmd "winget source add winget https://mirrors.ustc.edu.cn/winget-source --trust-level trusted --rainbow"
    
    # Write-Host "升级Winget..."
    # Run-InNewCmd "winget install Microsoft.AppInstaller --accept-source-agreements --accept-package-agreements --source winget --rainbow"

    # 调用BingWallpaper
    Get-BingWallpaper
  
    # 执行Check.ps1脚本（与当前脚本同目录）
    $scriptPath = Join-Path -Path $PSScriptRoot -ChildPath "Check.ps1"
    if (Test-Path $scriptPath) {
        Write-Host "正在执行Check.ps1脚本..."
        powershell -ExecutionPolicy Bypass -File $scriptPath
    }
    else {
        Write-Warning "未找到Check.ps1脚本，路径: $scriptPath"
    }

    # 执行Soft.ps1脚本（与当前脚本同目录）
    $scriptPath = Join-Path -Path $PSScriptRoot -ChildPath "Soft.ps1"
    if (Test-Path $scriptPath) {
        Write-Host "正在执行Soft.ps1脚本..."
        powershell -ExecutionPolicy Bypass -File $scriptPath
    }
    else {
        Write-Warning "未找到Soft.ps1脚本，路径: $scriptPath"
    }
}
else {
    # 未安装winget
    Write-Host "未检测到 winget" -ForegroundColor Yellow
    Write-Host "启动winget安装进程..."
    
    # 写入id.ini文件
    $iniPath = "id.ini"
    "WinGet" | Out-File -FilePath $iniPath -Encoding ASCII
    "9NBLGGH4NNS1" | Out-File -FilePath $iniPath -Encoding ASCII -Append
    Write-Host "已创建id.ini文件: $iniPath"
    
    # 执行AddApp.ps1脚本（与当前脚本同目录）
    $scriptPath = Join-Path -Path $PSScriptRoot -ChildPath "AddApp.ps1"
    if (Test-Path $scriptPath) {
        Write-Host "正在执行AddApp.ps1脚本..."
        & powershell -ExecutionPolicy Bypass -File $scriptPath
    }
    else {
        Write-Warning "未找到AddApp.ps1脚本，路径: $scriptPath"
        exit 1
    }

    # 确认winget已安装
    if (-not (Get-Command -Name winget -ErrorAction SilentlyContinue)) {
        Write-Error "Winget安装失败，请手动安装后重试"
        exit 1
    }
   
    Write-Host "WinGet 启动代理..."
    Run-InNewCmd "winget settings --enable ProxyCommandLineOptions"
    
    Write-Host "WinGet 移除源..."
    Run-InNewCmd "winget source remove winget --rainbow"
    
    Write-Host "WinGet 设置中科大源..."
    Run-InNewCmd "winget source add winget https://mirrors.ustc.edu.cn/winget-source --trust-level trusted --rainbow"

    # 调用BingWallpaper
    Get-BingWallpaper
    
    # 执行Check.ps1脚本（与当前脚本同目录）
    $scriptPath = Join-Path -Path $PSScriptRoot -ChildPath "Check.ps1"
    if (Test-Path $scriptPath) {
        Write-Host "正在执行Check.ps1脚本..."
        powershell -ExecutionPolicy Bypass -File $scriptPath
    }
    else {
        Write-Warning "未找到Check.ps1脚本，路径: $scriptPath"
    }

    # 执行Soft.ps1脚本（与当前脚本同目录）
    $scriptPath = Join-Path -Path $PSScriptRoot -ChildPath "Soft.ps1"
    if (Test-Path $scriptPath) {
        Write-Host "正在执行Soft.ps1脚本..."
        powershell -ExecutionPolicy Bypass -File $scriptPath
    }
    else {
        Write-Warning "未找到Soft.ps1脚本，路径: $scriptPath"
    }
}

Write-Host "所有操作已完成" -ForegroundColor Green
